package com.levi.controller;

import com.levi.domain.Base64Vo;
import com.levi.service.MongoService;
import com.mongodb.client.gridfs.GridFSBucket;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @author shentong
 * @since 2022/7/17 21:45
 */
@RestController
public class MongoController {


    @Autowired
    private GridFSBucket gridFSBucket;

    @Autowired
    private MongoService mongoService;

    /**
     * 使用GridFSBucket  上传图片文件
     * @param base64Vo
     * @return
     * @throws IOException
     */
    @PostMapping("upload")
    public String uploadPic(Base64Vo base64Vo) throws IOException {
        String img64 = base64Vo.getImg64();
        //将base64字符串转换为字节数组
        byte[] bytes = new BASE64Decoder().decodeBuffer(img64.trim());
        //将将字节数组转换为字节输入流
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        //获得文件的id
        ObjectId fileId = gridFSBucket.uploadFromStream("test1" +
                ".png", inputStream);
        String fileIdStr = fileId.toString();
        return fileIdStr;
    }

    /**
     * Sessions are not supported by the MongoDB cluster to which this client is connected
     * mongo单节点不支持事务
     * @return
     */
    @GetMapping("testTransaction")
    public String testTransaction() {
        String result = mongoService.testTransaction();
        return result;
    }

}
